
package de.swta.freezay.components;

import org.apache.wicket.ajax.AjaxRequestTarget;
import org.apache.wicket.ajax.markup.html.form.AjaxSubmitLink;
import org.apache.wicket.markup.html.form.Form;
import org.apache.wicket.markup.html.form.RequiredTextField;
import org.apache.wicket.markup.html.panel.FeedbackPanel;
import org.apache.wicket.markup.html.panel.Panel;
import org.apache.wicket.model.CompoundPropertyModel;
import org.apache.wicket.validation.IValidator;

/**
 *
 * @author Jan Korreck
 */
public abstract class TextInputPanel extends Panel {

    /**
     * Constructor
     *
     * @param id the markupID
     * @param validator the validator for this component
     * @param modelObject the model object of this component
     */
    public TextInputPanel(final String id, final IValidator validator,
            final Object modelObject) {

        super (id);

        /* create the form component */
        final Form inputForm = new Form("input");
        /* add a feedback panel to display messages */
        inputForm.add(new FeedbackPanel("feedback").setOutputMarkupId(true));

        /* create a required textfield */
        RequiredTextField textField = new RequiredTextField("value",
                modelObject.getClass());
        /* register the validator */
        textField.add(validator);

        /* set up the textfield model */
        textField.setModel(new CompoundPropertyModel(modelObject));
        inputForm.add(textField);

        /* set up the "on submit" behaviour */
        inputForm.add(new AjaxSubmitLink("submit") {
            // <editor-fold defaultstate="collapsed" desc="submit behaviour">
            @Override
            protected void onSubmit(AjaxRequestTarget target, Form<?> form) {
                submitClicked(target, 
                        ((RequiredTextField) inputForm.get("value"))
                        .getModelObject());
            }

             @Override
            protected void onError(AjaxRequestTarget target, Form<?> form) {
                target.addComponent(this.getParent().get("feedback"));
                super.onError(target, form);
            }
            // </editor-fold>
        });

        /* add the form component to this panel */
        add(inputForm);
    }

    /**
     * Called if submit button is clicked and no error occurs
     *
     * @param target the ajax request target
     * @param input the input object
     */
    public abstract void submitClicked(AjaxRequestTarget target, Object input);

}
